﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Jayden.Dll.Updater;

namespace Jayden.Windows.Updater
{
	public partial class UpdaterForm : Form
	{
		private string m_Path;
		private WebClient m_WebClient = new WebClient();
		private SoftwareVersionInformation m_Manifest = null;
		private string m_ApplicationPath;

		public UpdaterForm(string[] args)
		{
			InitializeComponent();

			try
			{
				string updateConfigFilepath = "update.config";
				string[] lines = File.ReadAllLines(updateConfigFilepath);
				m_Path = lines[0];
				Uri manifestUri = new Uri(lines[0] + lines[1]);
				m_ApplicationPath = lines[2];

				label.Text = "Cheking for updates ...";
				Refresh();
				m_WebClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted);
				m_WebClient.DownloadDataAsync(manifestUri, "Manifest");
			}
			catch
			{
				Application.Exit();
			}
		}
		protected override void OnClosed(EventArgs e)
		{
			base.OnClosed(e);
			Application.Exit();
		}

		void DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
		{
			if (e.Cancelled)
				return;
			if ((e.UserState as string) == "Manifest")
			{
				using (MemoryStream memoryStream = new MemoryStream(e.Result))
				{
					m_Manifest = new SoftwareVersionInformation(memoryStream);
				}
				for (int c = 0; c < m_Manifest.Count; c++)
				{
					FileVersionInformation latest = m_Manifest[c];
					FileVersionInformation current = new FileVersionInformation(latest.RelativePath);

					if (!current.Equals(latest))
					{
						Invoke((MethodInvoker)delegate()
						{
							label.Text = "Downloading " + latest.RelativePath + " ...";
							progressBar.Value = (c + 1) * 100 / m_Manifest.Count;
							Refresh();
						});
						if (File.Exists(latest.RelativePath))
							File.Delete(latest.RelativePath);
						m_WebClient.DownloadFile(m_Path + latest.RelativePath, latest.RelativePath);
					}
					else
					{
						Invoke((MethodInvoker)delegate()
						{
							label.Text = "";
							progressBar.Value = (c + 1) * 100 / m_Manifest.Count;
							Refresh();
						});
					}
				}
			}
			if (!string.IsNullOrWhiteSpace(m_ApplicationPath))
				System.Diagnostics.Process.Start(m_ApplicationPath);
			Application.Exit();
		}
	}
}
